//
//  HelpTextViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/6/26.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "HelpTextViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "LinLi.h"
#import "CommentReplyList.h"
#import "PeopleDataViewController.h"
#import "MJRefresh.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "HYActivityView.h"
#import "ReportDetailVC.h"
#import "PointsManager.h"
#import "MWPhoto.h"
#import "MWPhotoBrowser.h"
#import "UIImageView+EMWebCache.h"
#import "EMSDImageCache.h"
#import "DXMessageToolBar.h"
#import "ConvertToCommonEmoticonsHelper.h"
#import "PointsManager.h"
#import "LinLiTableViewCell.h"
#import "CommentTableViewCell.h"
#import "WFPopTwoView.h"
#import "UIColor+Addition.h"
#import "YMButton.h"
#import "PraiseListViewController.h"

#define VILLAGENOTIFICATION @"reloadLinLiTableView"
#define MYNOTIFICATION @"reloadMyVillageTableView"

@interface HelpTextViewController ()<UITextViewDelegate,MWPhotoBrowserDelegate,DXMessageToolBarDelegate,UIActionSheetDelegate>{
    
    NSMutableArray *contentArray,*photos;
    int contentPage;
    NSInteger contentClick;
    BOOL orReply,isDelectSelfComment;
    NSString *urlStr,*replyUserid,*itemid,*touserid;
    ReplyComment *currentReplyComment;
}

@property (nonatomic, strong) HYActivityView *activityView;
@property (strong, nonatomic) DXMessageToolBar *chatToolBar;
@property (nonatomic,strong) WFPopView *operationView;
@property (nonatomic,strong) NSIndexPath *openIndexPath;

@end

@implementation HelpTextViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if (_linLi.type==1) {
        self.title=@"帮忙正文";
    }else{
        self.title=@"话题正文";
    }
    
    orReply=NO;//判断是否是互相评论的回复
    contentClick=0;//记录当前点击行数
    isDelectSelfComment=NO;
    
    contentArray=[[NSMutableArray alloc]init];
    contentPage=1;
    [self getPraiseList];
    [self createTableView];
    [self createNavButton];
    [self addRefreshAttribute];
    [self.view addSubview:self.chatToolBar];//添加评论框
    
    if (_linLi.commentcount>0) {
        //获取评论列表
        [self getContentListWithType:_linLi.type andPage:1];
    }
}

-(void)createNavButton{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 25, 20);
    [rightBtn setImage:[UIImage imageNamed:@"nav_right_share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(more) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}

-(void)createTableView{
    
    _helpListTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-100) style:UITableViewStyleGrouped];
    _helpListTableView.dataSource=self;
    _helpListTableView.delegate=self;
    _helpListTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _helpListTableView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_helpListTableView];
    
    if ([_helpListTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_helpListTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_helpListTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_helpListTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)keyBoardHidden{
    
    [self.chatToolBar endEditing:YES];
    orReply=NO;
    isDelectSelfComment=NO;
    contentClick=0;
    _chatToolBar.inputTextView.text=@"";
    _chatToolBar.inputTextView.placeHolder=@"我来说两句";
}

- (DXMessageToolBar *)chatToolBar{
    
    if (_chatToolBar == nil) {
        _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight], ScreenWidth, [DXMessageToolBar defaultHeight])];
        _chatToolBar.isComment=YES;
        _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _chatToolBar.delegate = self;
    }
    return _chatToolBar;
}

- (void)addRefreshAttribute{
    
    __weak typeof(self) weakSelf = self;
    
    [self.helpListTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
    if (_linLi.commentcount==0) {
        [self.helpListTableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
    }
}

- (void)reloadDataToNew:(BOOL)new{
    
    contentPage=contentPage+1;
    [self  getContentListWithType:_linLi.type andPage:contentPage];
}

-(void)more{
    
    if ([Config isShield]) {
        [self showAlertWithMessage:@"您已被村联络员屏蔽在该村的发言。如需申诉,请到“我-消息-通讯录”中与联络员进行联系"];
        return;
    }
    [self.view endEditing:YES];
    __weak typeof(self) weakSelf = self;
    
    if (!self.activityView) {
        self.activityView = [[HYActivityView alloc]initWithTitle:@"分享到" referView:self.view];
        
        //横屏会变成一行6个, 竖屏无法一行同时显示6个, 会自动使用默认一行4个的设置.
        self.activityView.numberOfButtonPerLine = 6;
        
        
        ButtonView *bv = [[ButtonView alloc]initWithText:@"QQ" image:[UIImage imageNamed:@"cunli_qqFriend"] handler:^(ButtonView *buttonView){
            NSLog(@"点击QQ");
            
            [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
            [UMSocialData defaultData].extConfig.qqData.title = self.linLi.introduce;
            
            [UMSocialData defaultData].extConfig.qqData.url = self.linLi.share_url;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ] content:self.linLi.share_url image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                if (response.responseCode == UMSResponseCodeSuccess) {
                    NSLog(@"QQ分享成功");
                    //获取分享积分
                    [PointsManager sendSharePointWithChannel:@"4" andItemid:_linLi.itemid];
                }
            }];
            
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"QQ空间" image:[UIImage imageNamed:@"cunli_qqZone"] handler:^(ButtonView *buttonView){
            //            NSLog(@"点击QQ空间");
            
            [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
            [UMSocialData defaultData].extConfig.qzoneData.title = self.linLi.introduce;
            [UMSocialData defaultData].extConfig.qzoneData.url = self.linLi.share_url;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQzone] content:self.linLi.introduce image:[UIImage imageNamed:@"aboutApp01.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //                    NSLog(@"QQ空间分享成功");
                    
                    [PointsManager sendSharePointWithChannel:@"3" andItemid: _linLi.itemid];
                }
            }];
            
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"微信" image:[UIImage imageNamed:@"cunli_wechatFriend"] handler:^(ButtonView *buttonView){
            
            //            NSLog(@"点击微信");
            
            [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
            [UMSocialData defaultData].extConfig.wechatSessionData.url = self.linLi.share_url;
            [UMSocialData defaultData].extConfig.title = self.linLi.introduce;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession] content:self.linLi.introduce image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                //                NSLog(@"分享成功");
                
                [PointsManager sendSharePointWithChannel:@"1" andItemid:_linLi.itemid];
            }];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"朋友圈" image:[UIImage imageNamed:@"cunli_wechatTimeline"] handler:^(ButtonView *buttonView){
            //            NSLog(@"朋友圈");
            
            [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
            [UMSocialData defaultData].extConfig.wechatTimelineData.url = self.linLi.share_url;
            [UMSocialData defaultData].extConfig.title = self.linLi.introduce;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline] content:self.linLi.introduce image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                //                NSLog(@"分享成功");
                
                [PointsManager sendSharePointWithChannel:@"2" andItemid: _linLi.itemid];
            }];
            
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"举报" image:[UIImage imageNamed:@"cunli_report"] handler:^(ButtonView *buttonView){
            [weakSelf doReportAction];
        }];
        [self.activityView addButtonView:bv];
        
        if ([[Config getOwnUserID] isEqualToString:_linLi.userid]||[[Config getGroupID] isEqualToString:@"9"]) {
            //删帖
            bv = [[ButtonView alloc]initWithText:@"删除" image:[UIImage imageNamed:@"delete_articl"] handler:^(ButtonView *buttonView){
                [weakSelf showAlertWithTag:1001];
            }];
            [self.activityView addButtonView:bv];
        }
    }
    
    [self.activityView show];
}

#pragma mark -举报文章

- (void)doReportAction{
    
    ReportDetailVC *reportVC = [[ReportDetailVC alloc] init];
    reportVC.itemid = _linLi.itemid;
    reportVC.m_itemid = _linLi.item_mid;
    [self.navigationController pushViewController:reportVC animated:YES];
}

-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -发送评论

- (void)didSendText:(NSString *)text{
    
    if ([text isEqualToString:@""]) {
        [self showAlertWithMessage:@"输入内容不能为空"];
        return;
    }else{
        NSString *willSendText = [ConvertToCommonEmoticonsHelper convertToCommonEmoticons:text];
        [self sendContentWithString:willSendText];
    }
}

-(void)sendContentWithString:(NSString *)commentString{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    
    if (contentClick==0) {
        
        urlStr=@"comment.php";
        [CheckParams setObject: _linLi.item_mid forKey:@"item_mid"];
        [CheckParams setObject: _linLi.itemid forKey:@"itemid"];
        [CheckParams setObject:commentString forKey:@"content"];
        
    }else{
        
        urlStr=@"replycomment.php";
        CommentReplyList *comment=[contentArray objectAtIndex:contentClick-1];
        [CheckParams setObject:commentString forKey:@"content"];
        if (orReply) {
            [CheckParams setObject:currentReplyComment.userid forKey:@"touserid"];
        }else{
            [CheckParams setObject:comment.userid forKey:@"touserid"];
        }
        [CheckParams setObject:comment.itemid forKey:@"itemid"];
    }
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:urlStr httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        NSString *responseString=[urlStr isEqualToString:@"replycomment.php"]?@"replycomment":@"comment";
        if ([[result objectForKey:@"response"] isEqualToString:responseString]) {
            
            [Config showHUDWithText:@"评论发送成功!" andImage:@"done"];
            
            //新增评论刷新评论数
            if ([urlStr isEqualToString:@"comment.php"]) {
                _linLi.commentcount+=1;
                LinLiTableViewCell *linliCell =(LinLiTableViewCell *)[_helpListTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                [linliCell reloadCommentCountWithLinLi:_linLi];
                if (_isVillage) {
                    [self sendNotificationWithActionName:@"commentCountChange" andNotificationName:VILLAGENOTIFICATION andLinLi:_linLi];
                }else{
                    [self sendNotificationWithActionName:@"commentCountChange" andNotificationName:MYNOTIFICATION andLinLi:_linLi];
                }
            }
            
            [contentArray removeAllObjects];
            [self getContentListWithType:_linLi.type andPage:1];
            contentPage=1;
            
        }else{
            
            NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (str) {
                [self showAlertWithMessage:str];
            }else{
                [self showAlertWithMessage:@"评论发送失败!"];
            }
        }
        [self restoreInputTextView];
        
    }failureAction:^{
        [self showAlertWithMessage:@"网络错误!"];
        [self restoreInputTextView];
    }];
}

-(void)restoreInputTextView{
    
    orReply=NO;
    contentClick=0;
    _chatToolBar.inputTextView.text=@"";
    _chatToolBar.inputTextView.placeHolder=@"我来说两句";
    [self keyBoardHidden];
}

-(void)getContentListWithType:(int)type andPage:(int)page{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",type] forKey:@"type"];
    [CheckParams setObject:_linLi.itemid forKey:@"itemid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [CheckParams setObject:@"10" forKey:@"pagesize"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"replycommentlist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        [self.helpListTableView.legendFooter endRefreshing];
        
        if ([[result objectForKey:@"response"] isEqualToString:@"relpycommentlist"]) {
            
            NSDictionary *dic=[result objectForKey:@"data"];
            NSArray *listArray=[dic objectForKey:@"commentlist"];
            int totalcount=[[dic objectForKey:@"totalcount"] intValue];
            
            for (NSDictionary *dic in listArray) {
                //CommentReplyList *content=[[CommentReplyList alloc]initWithDictionary:dic];
                CommentReplyList *content=[CommentReplyList yy_modelWithDictionary:dic];
                NSString *contentText = [ConvertToCommonEmoticonsHelper convertToSystemEmoticons:content.content];
                content.commentHeight=[self commentHeightWithString:contentText];
                content.content=contentText;
                [contentArray addObject:content];
            }
            
            if (contentArray.count==totalcount) {
                [self.helpListTableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            }
            [self.helpListTableView reloadData];
        }
        
    }failureAction:^{
        [self.helpListTableView.legendFooter endRefreshing];
    }];
}

#pragma mark - UITableView代理

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return contentArray.count+1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==0) {
        
        float cellHeight=_linLi.contentHeight+_linLi.praiseNameHeight+105;
        if (_linLi.pics.count>0) {
            
            if (_linLi.pics.count==1) {
                
                float height=[self onePicHeightWithWidth:_linLi.first_pic_width andHeight:_linLi.first_pic_height];
                cellHeight=cellHeight+height+10;
            }else{
                float imgWidth=ceilf((ScreenWidth-40)/3.0);
                cellHeight=cellHeight+(_linLi.pics.count+2)/3*(imgWidth+5)+5;
            }
        }
        if (_type!=1&&_linLi.s_area.length>0) {
            cellHeight=cellHeight+20;
        }
        return cellHeight;
        
    }else{
        
        CommentReplyList *content=[contentArray objectAtIndex:indexPath.row-1];
        //float cellHeight=[self heightWithString:content.content]+35;
        
        float cellHeight=content.commentHeight+65;
        
        for (int i=0; i<content.replylist.count; i++) {
            
            NSDictionary *replyDic=[content.replylist objectAtIndex:i];
            NSString *replyString=[NSString stringWithFormat:@"%@回复%@:%@",[replyDic objectForKey:@"totruename"],[replyDic objectForKey:@"truename"],[replyDic objectForKey:@"content"]];
            NSString *commentReplyText = [ConvertToCommonEmoticonsHelper
                                          convertToSystemEmoticons:replyString];
            float replyHeight=[self commentHeightWithString:commentReplyText];
            cellHeight=cellHeight+replyHeight;
        }
        return cellHeight;
    }
}

-(float)onePicHeightWithWidth:(float)width andHeight:(float)height{
    
    float picHeight;
    if (width<ScreenWidth-30&&height<250) {
        picHeight=height;
    }else{
        if(width>ScreenWidth-30&&height<250) {
            picHeight=(ScreenWidth-30)*height/width;
        }else if(width<ScreenWidth-30&&height>250){
            picHeight=250;
        }else if(width>ScreenWidth-30&&height>250){
            picHeight=(ScreenWidth-30)*height/width;
        }else{
            float imgWidth=ceilf((ScreenWidth-40)/3.0);
            picHeight=imgWidth;
        }
    }
    return ceilf(picHeight);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==0) {
        
        static NSString *cellIdentifier=@"cell";
        
        LinLiTableViewCell *cell =(LinLiTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        if (!cell) {
            
            cell = [[LinLiTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier andLinLi:_linLi andRange:_type];
        }
        
        cell.selectedIndexPath=indexPath;
        cell.goToPersonInfo=^(NSInteger currentRow){
            //查看个人信息
            [self goToPersonInfoWithUserid:nil];
        };
        cell.addLike=^(NSInteger currentRow){
            //点赞
            [self praiseButtonClick];
        };
        cell.checkBigPics=^(NSInteger currentRow,NSInteger currentPage){
            //点击图片
            [self checkBigPicWithCurrentPage:currentPage];
        };
        cell.goToPraisePersonInfo=^(NSString *userid){
            if ([userid isEqualToString:@"查看全部>"]) {
                [self goToPraiseListVC];
            }else{
                [self goToPersonInfoWithUserid:userid];
            }
        };
        return cell;
        
    }else{
        
        CommentReplyList *content=[contentArray objectAtIndex:indexPath.row-1];
        static NSString *cellIdentifier=@"comment";
        CommentTableViewCell *cell =(CommentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        if (!cell) {
            cell = [[CommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier andComment:content];
        }
        
        cell.selectedIndexPath=indexPath;
        cell.goToPersonInfo=^(NSInteger currentRow){
            //查看个人信息
            [self lookPersonInfo:currentRow];
        };
        //互相回复评论点击事件
        cell.replyComment=^(NSInteger currentRow,NSInteger currentReply){
            [self replyCommentWithRow:currentRow andCurrentReply:currentReply];
        };
        //展开按钮绑定事件
        [cell.moreButton addTarget:self action:@selector(showMoreButton:) forControlEvents:UIControlEventTouchUpInside];
        cell.moreButton.appendIndexPath=indexPath;
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [self.operationView dismiss];
    
    contentClick=indexPath.row;
    orReply=NO;
    
    if (indexPath.row==0) {
        [_chatToolBar.inputTextView becomeFirstResponder];
        _chatToolBar.inputTextView.placeHolder=@"我来说两句";
        _chatToolBar.inputTextView.text=@"";
    }else{
        CommentReplyList *content=[contentArray objectAtIndex:indexPath.row-1];
        if ([content.userid isEqualToString:[Config getOwnUserID]]) {
            [self keyBoardHidden];
            isDelectSelfComment=YES;
            contentClick=indexPath.row;
            [self showDelectActionSheetWithTag:333];
        }else{
            [_chatToolBar.inputTextView becomeFirstResponder];
            _chatToolBar.inputTextView.placeHolder=[NSString stringWithFormat:@"回复%@",content.truename];
            _chatToolBar.inputTextView.text=@"";
        }
    }
}

#pragma mark - 点击互相回复评论

-(void)replyCommentWithRow:(NSInteger)currentRow andCurrentReply:(NSInteger)currentReply{
    
    [self.operationView dismiss];
    contentClick=currentRow;
    CommentReplyList *content=[contentArray objectAtIndex:currentRow-1];
    currentReplyComment=[ReplyComment yy_modelWithDictionary:[content.replylist objectAtIndex:currentReply]];
    if ([currentReplyComment.userid isEqualToString:[Config getOwnUserID]]) {
        [self keyBoardHidden];
        isDelectSelfComment=YES;
        [self showDelectActionSheetWithTag:222];
    }else{
        [_chatToolBar.inputTextView becomeFirstResponder];
        _chatToolBar.inputTextView.text=@"";
        _chatToolBar.inputTextView.placeHolder=[NSString stringWithFormat:@"回复%@",currentReplyComment.truename];
        orReply=YES;
    }
}

-(void)showDelectActionSheetWithTag:(NSInteger)sheetTag{
    
    UIActionSheet *delectSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:nil, nil];
    delectSheet.tag=sheetTag;
    [delectSheet showInView:self.view];
}

#pragma mark -actionSheet代理方法

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        if (actionSheet.tag==333) {
            [self delectComment];
        }else if (actionSheet.tag==222){
            [self delectMyReplyComment];
        }
    }else{
        NSLog(@"fshfhsfgngfnfgnsfgns");
        [self keyBoardHidden];
    }
}

#pragma mark -查看个人信息

-(void)goToPersonInfoWithUserid:(NSString *)userid{
    
    PeopleDataViewController *dataVC=[[PeopleDataViewController alloc]init];
    if (userid) {
        dataVC.touserid=userid;
    }else{
        dataVC.touserid= _linLi.userid;
    }
    [self.navigationController pushViewController:dataVC animated:YES];
}

-(void)lookPersonInfo:(NSInteger)row{
    
    PeopleDataViewController *dataVC=[[PeopleDataViewController alloc]init];
    CommentReplyList *content=[contentArray objectAtIndex:row-1];
    dataVC.touserid=content.userid;
    [self.navigationController pushViewController:dataVC animated:YES];
}

#pragma mark -查看大图

-(void)checkBigPicWithCurrentPage:(NSInteger)page{
    
    photos = [NSMutableArray array];
    for (NSString *urlString in _linLi.big_pics) {
        [photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlString]]];
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.isScrollerPic=YES;
    [browser setCurrentPhotoIndex:page];
    [self.navigationController pushViewController:browser animated:YES];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    
    return photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    
    if (index < photos.count) {
        return [photos objectAtIndex:index];
    }
    return nil;
}

#pragma mark -点赞

-(void)praiseButtonClick{
    
    NSString *urlString=_linLi.is_prase==0?@"topicpraise.php":@"cancel_prase.php";
    NSString *responseString=_linLi.is_prase==0?@"topicpraise":@"cancel_prase";
    NSString *remaindString=_linLi.is_prase==0?@"点赞成功":@"取消赞成功";
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject: _linLi.itemid forKey:@"itemid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",_linLi.type] forKey:@"type"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:urlString httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:responseString]) {
            
            [self getPraiseList];
            
            [Config showHUDWithText:remaindString andImage:@"done"];
            //改变点赞行的赞个数
            if (_linLi.is_prase==0) {
                _linLi.is_prase=1;
                _linLi.look=_linLi.look+1;
            }else{
                _linLi.is_prase=0;
                _linLi.look=_linLi.look-1;
            }
            
            LinLiTableViewCell *linliCell =(LinLiTableViewCell *)[_helpListTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            [linliCell reloadPraiseWithLinLi:_linLi];
            if (_isVillage) {
                [self sendNotificationWithActionName:@"praiseChange" andNotificationName:VILLAGENOTIFICATION andLinLi:_linLi];
            }else{
                [self sendNotificationWithActionName:@"praiseChange" andNotificationName:MYNOTIFICATION andLinLi:_linLi];
            }
            
        }else{
            NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (str) {
                [Config showHUDWithText:str andImage:@"error"];
            }else{
                [Config showHUDWithText:@"操作失败!" andImage:@"error"];
            }
        }
        
    }failureAction:^{
        [Config showHUDWithText:@"网络错误!" andImage:@"error"];
    }];
}

- (void)showAlertWithMessage:(NSString *)message{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.operationView dismiss];
    [self.view endEditing:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
}

#pragma mark -删帖(联络员和本人调同一个接口)

-(void)showAlertWithTag:(NSInteger )alertTag{
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    alert.tag=alertTag;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==1) {
        
        if (alertView.tag==1001) {
            [self delectArticle];
        }else if (alertView.tag==2002){
            [self delectComment];
        }
    }
}

-(void)delectArticle{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_linLi.itemid forKey:@"itemid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",self.linLi.type+2] forKey:@"type"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"del_article.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        if ([[result objectForKey:@"response"] isEqualToString:@"del_article"]) {
            
            [Config showHUDWithText:@"删除成功!" andImage:@"done"];
            
            if (self.isVillage) {
                [self sendNotificationWithActionName:@"delectContent" andNotificationName:VILLAGENOTIFICATION andLinLi:nil];
            }else{
                [self sendNotificationWithActionName:@"delectContent" andNotificationName:MYNOTIFICATION andLinLi:nil];
            }
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            
            NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (str) {
                [Config showHUDWithText:str andImage:@"error"];
            }else{
                [Config showHUDWithText:@"删除失败!" andImage:@"error"];
            }
        }
        
    }failureAction:^{
        [Config showHUDWithText:@"网络错误删除失败!" andImage:@"error"];
    }];
}

#pragma mark - 按钮动画

- (void)showMoreButton:(YMButton *)sender{
    
    CGRect rectInTableView = [_helpListTableView rectForRowAtIndexPath:sender.appendIndexPath];
    CGFloat origin_Y = rectInTableView.origin.y + sender.frame.origin.y;
    CGRect targetRect = CGRectMake(CGRectGetMinX(sender.frame), origin_Y, CGRectGetWidth(sender.bounds), CGRectGetHeight(sender.bounds));
    if (self.operationView.shouldShowed) {
        [self.operationView dismiss];
        return;
    }
    _openIndexPath=sender.appendIndexPath;
    [self.operationView showAtView:_helpListTableView rect:targetRect isFavour:NO];
}

#pragma mark -移除展开的按钮

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self.operationView dismiss];
    [self keyBoardHidden];
}

#pragma mark -点击展开的按钮事件

- (WFPopView *)operationView {
    
    if (!_operationView) {
        _operationView = [WFPopView initailzerWFOperationView];
        
        __weak __typeof(self)weakSelf = self;
        
        _operationView.didSelectedOperationCompletion = ^(WFOperationType operationType) {
            switch (operationType) {
                case WFOperationTypeReport:
                    [weakSelf reportComment];
                    break;
                case WFOperationTypeDelect:
                    [weakSelf showAlertWithTag:2002];
                    break;
                default:
                    break;
            }
        };
    }
    return _operationView;
}

#pragma mark -举报评论

- (void)reportComment{
    
    CommentReplyList *content=[contentArray objectAtIndex:_openIndexPath.row-1];
    ReportDetailVC *reportVC = [[ReportDetailVC alloc] init];
    reportVC.itemid = content.itemid;
    reportVC.m_itemid = @"10";
    [self.navigationController pushViewController:reportVC animated:YES];
}

#pragma mark -删除评论

- (void)delectComment{
    
    CommentReplyList *content;
    if (isDelectSelfComment) {
        content=[contentArray objectAtIndex:contentClick-1];
    }else{
        content=[contentArray objectAtIndex:_openIndexPath.row-1];
    }
    NSString *type=[NSString stringWithFormat:@"%d",_linLi.type+2];
    NSString *itemid1=content.itemid;
    [PointsManager delectCommentWithType:type itemid:itemid1 completionBlock:^(BOOL isSuccess){
        
        if (isSuccess) {
            
            [Config showHUDWithText:@"删除评论成功!" andImage:@"done"];
            
            _linLi.commentcount-=1;
            LinLiTableViewCell *linliCell =(LinLiTableViewCell *)[_helpListTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            [linliCell reloadCommentCountWithLinLi:_linLi];
            
            if (_isVillage) {
                [self sendNotificationWithActionName:@"commentCountChange" andNotificationName:VILLAGENOTIFICATION andLinLi:_linLi];
            }else{
                [self sendNotificationWithActionName:@"commentCountChange" andNotificationName:MYNOTIFICATION andLinLi:_linLi];
            }
            
            contentPage=1;
            [contentArray removeAllObjects];
            [self getContentListWithType:_linLi.type andPage:1];
            
        }else{
            
            [Config showHUDWithText:@"删除评论失败!" andImage:@"error"];
        }
        
    }];
    //评论框恢复原来
    [self keyBoardHidden];
}

#pragma mark -删除自己的互相评论

- (void)delectMyReplyComment{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:currentReplyComment.itemid forKey:@"itemid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"del_replycomment.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"del_replycomment"]) {
            
            [Config showHUDWithText:@"删除成功!" andImage:@"done"];
            contentPage=1;
            [contentArray removeAllObjects];
            [self getContentListWithType:_linLi.type andPage:1];
            
        }else{
            
            NSString *errorString=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (errorString) {
                [Config showHUDWithText:errorString andImage:@"error"];
            }else{
                [Config showHUDWithText:@"删除失败!" andImage:@"error"];
            }
        }
        
    }failureAction:^{
        [Config showHUDWithText:@"网络错误!" andImage:@"error"];
    }];
    [self keyBoardHidden];
}

-(float)commentHeightWithString:(NSString *)introduce{
    
    CGRect rect = [introduce boundingRectWithSize:CGSizeMake(ScreenWidth-90, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f]} context:nil];
    CGFloat height = ceilf(rect.size.height);
    return height+5;
}

-(void)sendNotificationWithActionName:(NSString *)actionName andNotificationName:(NSString *)notificationName andLinLi:(LinLi *)linLi{
    
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
    [dict setObject:[NSString stringWithFormat:@"%d",_type] forKey:@"type"];
    [dict setObject:actionName forKey:@"name"];
    if (linLi) {
        [dict setObject:linLi forKey:@"content"];
    }
    NSNotification *notification =[NSNotification notificationWithName:notificationName object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

-(void)goToPraiseListVC{
    
    PraiseListViewController *praiseVC=[[PraiseListViewController alloc]init];
    praiseVC.type=[NSString stringWithFormat:@"%d",_linLi.type];
    praiseVC.itemid=_linLi.itemid;
    [self.navigationController pushViewController:praiseVC animated:YES];
}

-(void)getPraiseList{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_linLi.itemid forKey:@"itemid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",_linLi.type]  forKey:@"type"];
    [CheckParams setObject:@"1" forKey:@"page"];
    [CheckParams setObject:@"20" forKey:@"pagesize"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"get_member_prase.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@">>>>%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"get_member_prase"]) {
            
            NSArray *listArray=[result objectForKey:@"list"];
            NSInteger count=listArray.count;
            _linLi.praiseListArray=listArray;
            
            if (listArray.count>0) {
                
                NSString *praiseString=@"";
                
                for (int i=0;i<count;i++) {
                    
                    PraiseInfo *info=[PraiseInfo yy_modelWithDictionary:[listArray objectAtIndex:i]];
                    if (i==19||i<count-1) {
                        praiseString=[NSString stringWithFormat:@"%@%@,   ",praiseString,info.truename];
                    }else{
                        praiseString=[NSString stringWithFormat:@"%@%@",praiseString,info.truename];
                    }
                }
                
                if (count==20) {
                    _linLi.praiseNameString=[NSString stringWithFormat:@"%@查看全部>",praiseString];
                }else{
                    _linLi.praiseNameString=praiseString;
                }
                _linLi.praiseNameHeight=[self commentHeightWithString:_linLi.praiseNameString];
            }else{
                _linLi.praiseNameString=nil;
                _linLi.praiseNameHeight=0;
            }
            
            [_helpListTableView reloadData];
        }
        
    }failureAction:^{
        
    }];
}

@end
